import router from '@/router'
import { ErrorPageNameMap, PageEnum } from '@/enums/pageEnum'
import { ResultEnum } from '@/enums/httpEnum'

export const routerTurnByName = (pageName: string, isReplace?: boolean, windowOpen?: boolean) => {
  if (windowOpen) {
    const path = fetchPathByName(pageName, 'href')
    openNewWindow(path as string)
    return
  }
  if (isReplace) {
    router.replace({ name: pageName })
    return
  }
  router.push({
    name: pageName
  })
}

export const fetchPathByName = (pageName: string, p?: 'href') => {
  try {
    const pathData = router.resolve({ name: pageName })
    return p ? pathData[p] : pathData
  } catch (error) {
    window.$message.warning('查询路由信息失败，请联系管理员！')
  }
}

export const openNewWindow = (url: string) => {
  return window.open(url, '_blank')
}

export const reloadRoutePage = () => {
  routerTurnByName(PageEnum.RELOAD_NAME)
}

// 判断是否是预览页
export const isPreview = () => {
  return document.location.hash.includes('preview')
}

// 错误页重定向
export const redirectErrorPage = (code: ResultEnum) => {
  if (!code) return false
  const pageName = ErrorPageNameMap.get(code)
  if (!pageName) return false
  routerTurnByName(pageName)
}
